﻿using Microsoft.Win32;
using SqlSugar;
using Study.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp4
{
    /// <summary>
    /// MyMenu.xaml 的交互逻辑
    /// </summary>
    public partial class MyMenu : Window
    {
        public MyMenu()
        {
            InitializeComponent();

            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = "Server = localhost; Database = wpf; Uid = root; Pwd = 123456; ",
                IsAutoCloseConnection = true,
                DbType = DbType.MySql
            };
            using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
            {
                List<MenuDatabase> list = db.Queryable<MenuDatabase>().ToList();
                List<MenuModel> menus = new List<MenuModel>();
                var firstLevel = list.Where(m => m.ParentId == 0).Select(p=>new MenuModel() 
                { 
                    Id=p.Id,
                    Name=p.Name
                }).ToList();
                foreach (var item in firstLevel)
                {
                    MenuModel menuModel = new MenuModel()
                    {
                        Id = item.Id,
                        Name = item.Name
                    };
                    BuildMenu(list, item);
                }
                menus.AddRange(firstLevel);
                _Menu.ItemsSource = menus;
            }
        }

        private void BuildMenu(List<MenuDatabase> list,MenuModel menuModel)
        {
            foreach (var item in list.Where(m => m.ParentId == menuModel.Id))
            {
                MenuModel menu = new MenuModel()
                {
                    Id = item.Id,
                    Name = item.Name
                };
                menuModel.Children.Add(menu);
                BuildMenu(list, menu);
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "文本文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == true)
            {
                _ = System.Diagnostics.Process.Start("Notepads.exe", dialog.FileName);
            }
        }
    }
}
